package com.stsolutions.budgetcontroller.db;

import java.sql.SQLException;
import java.util.Collection;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.stsolutions.budgetcontroller.model.data.Cost;
import com.stsolutions.budgetcontroller.model.data.CostBucket;
import com.stsolutions.budgetcontroller.model.data.CostType;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
	protected final String LOG_TAG = getClass().getSimpleName();

	// name of the database file for your application -- change to something
	// appropriate for your app
	private static final String DATABASE_NAME = "budget_test_3.db";
	// any time you make changes to your database objects, you may have to
	// increase the database version
	private static final int DATABASE_VERSION = 1;

	// the DAO object we use to access the Cost table
	private Dao<Cost, Integer> costDao = null;
	private RuntimeExceptionDao<Cost, Integer> costRuntimeDao = null;

	private RuntimeExceptionDao<Object, Integer> runtimeDao = null;
	private Dao<Object, Integer> dao = null;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	public Class<?> getClass(DaoObject daoObject) {
		switch (daoObject) {
		case COST:
			return Cost.class;
		case COST_TYPE:
			return CostType.class;
		case COST_BUCKET:
			return CostBucket.class;
		default:
			return null;
		}

	}

	@Override
	public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, CostBucket.class);
			TableUtils.createTable(connectionSource, CostType.class);
			TableUtils.createTable(connectionSource, Cost.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}

	}

	/**
	 * This is called when your application is upgraded and it has a higher
	 * version number. This allows you to adjust the various data to match the
	 * new version number.
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
			int oldVersion, int newVersion) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onUpgrade");
			TableUtils.dropTable(connectionSource, CostBucket.class, true);
			// after we drop the old databases, we create the new ones
			onCreate(db, connectionSource);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
			throw new RuntimeException(e);
		}
	}

	// GENERIC getRuntimeDao method
	// TODO optimization to be singleton, and to pull from hashmap of objects
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public RuntimeExceptionDao<Object, Integer> getRuntimeDao(Class clazz) {
		runtimeDao = getRuntimeExceptionDao(clazz);
		return runtimeDao;
	}

	// GENERIC getDao method
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Dao<Object, Integer> getCostBucketDao(Class clazz)
			throws SQLException {
		dao = getDao(clazz);
		return dao;
	}

	/**
	 * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao
	 * for our Cost class. It will create it or just give the cached value.
	 * RuntimeExceptionDao only through RuntimeExceptions.
	 */
	public RuntimeExceptionDao<Cost, Integer> getCostRuntimeDao() {
		if (costRuntimeDao == null) {
			costRuntimeDao = getRuntimeExceptionDao(Cost.class);
		}
		return costRuntimeDao;
	}

	/**
	 * Returns the Database Access Object (DAO) for our Cost class. It will
	 * create it or just give the cached value.
	 */
	public Dao<Cost, Integer> getCostDao() throws SQLException {
		if (costDao == null) {
			costDao = getDao(Cost.class);
		}
		return costDao;
	}

	/**
	 * Close the database connections and clear any cached DAOs.
	 */
	@Override
	public void close() {
		super.close();
		dao = null;
		runtimeDao = null;
	}

	@SuppressWarnings("unchecked")
	public Object doDataBaseAction(int action, Object objectData,
			Object listData, DaoObject daoObject) {
		// get our dao

		Class<?> clazz = getClass(daoObject);
		Log.i(LOG_TAG, "Get data for class: " + clazz.getCanonicalName());
		RuntimeExceptionDao<Object, Integer> dao = getRuntimeDao(clazz);

		switch (action) {

		case DataBaseActions.ACTION_GET_ALL: {
			Collection<Object> adapterItems = dao.queryForAll();
			dao.getDataClass();
			// our string builder for building the content-view
			Log.i(LOG_TAG, "Got All data from db."
					+ dao.getDataClass().getCanonicalName());
			Log.i(LOG_TAG, "Data list size:" + adapterItems.size());
			return adapterItems;
		}
		case DataBaseActions.ACTION_SAVE_ITEM: {
			Collection<Object> objects = (Collection<Object>) listData;
			Log.i(LOG_TAG, "Add new data to db." + objectData);
			dao.create(objectData);
			if (objects != null)
				objects.add(objectData);
			Log.i(LOG_TAG, "Added to db." + objectData.toString());
			return objects;
		}
		case DataBaseActions.ACTION_SAVE_ITEM_FOREIGN: {
			Collection<Object> objects = (Collection<Object>) listData;
			Log.i(LOG_TAG, "Add new data to db:" + objectData);
			dao.create(objectData);
			Log.i(LOG_TAG, "Added to db:" + objectData.toString());
			return objects;
		}

		case DataBaseActions.ACTION_GET_ITEM_BY_ID: {
			Log.i(LOG_TAG, "Quering for id: " + (Integer) objectData);
			Object obj = dao.queryForId((Integer) objectData);
			// our string builder for building the content-view
			Log.i(LOG_TAG, "Got object from db." + System.currentTimeMillis());
			Log.i(LOG_TAG, "Object from db:" + obj.toString());
			return obj;
		}

		case DataBaseActions.ACTION_DELETE_ITEM: {

			Log.i(LOG_TAG, "Deleting object: " + objectData);
			// int objectId = getObjectId(objectData, daoObject);
			int idDeleted = dao.delete(objectData);
			// our string builder for building the content-view
			Log.i(LOG_TAG,
					"Deleting object from db." + System.currentTimeMillis());
			Log.i(LOG_TAG, "Object from db:" + idDeleted);

			Collection<Object> objects = (Collection<Object>) listData;
			if (objects != null) {
				Log.i(LOG_TAG, "List size:" + objects.size());
				objects.remove(objectData);
				Log.i(LOG_TAG, "Object from list:" + objectData);
				Log.i(LOG_TAG, "List size:" + objects.size());
			}

			return idDeleted;
		}

		default:
			return null;
		}
	}

	@SuppressWarnings("unused")
	private int getObjectId(Object objectData, DaoObject daoObject) {
		int id = -1;
		switch (daoObject) {

		case COST:
			id = ((Cost) objectData).getId();
			break;
		case COST_BUCKET:
			id = ((CostBucket) objectData).getCostBucketId();
			break;
		case COST_TYPE:
			id = ((CostType) objectData).getCostTypeId();
			break;
		default:
			break;
		}

		return id;
	}
}
